package com.bluexmicro.ota2.ui.screen.config

import android.content.Context
import android.graphics.Color
import androidx.lifecycle.ViewModel
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.ValueFormatter
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow

class ConfigViewModel : ViewModel() {


    val src = MutableList(30) { 20f }

    val ready = YaraCore.deviceReady

    private val _lineData = MutableStateFlow(loadLineData())
    val lineData = _lineData.asStateFlow()

    fun setValue(i: Int, value: Float) {
        src[i] = value
        _lineData.value = loadLineData()
    }

    fun save(context: Context) {
        val values = src.map { it.toInt().toByte() }.toByteArray()
        YaraCore.debugPowers(context, values)
    }


    private fun loadLineData(): LineData {

        val entries = src.mapIndexed { index, v ->
            Entry(index.toFloat(), v)
        }

        val lineDataSet = LineDataSet(entries, "Unit：W").apply {
            color = Color.GRAY
            setDrawCircles(true)
            setDrawValues(true)
            circleRadius = 1f
            valueTextColor = Color.DKGRAY // 设置值的文本颜色
            valueTextSize = 6f // 设置值的文本大小（单位：sp）
            mode = LineDataSet.Mode.CUBIC_BEZIER
            cubicIntensity = 0.1f

            valueFormatter = object : ValueFormatter() {
                override fun getFormattedValue(value: Float): String {
                    return value.toInt().toString()
                }
            }
            axisDependency = YAxis.AxisDependency.RIGHT
        }

        return LineData(lineDataSet)
    }

    fun tryConnect(context: Context, address: String) {
        YaraCore.tryConnect(context, address)
    }

    override fun onCleared() {
        super.onCleared()
        YaraCore.resetConnection()
    }
}